<template>
  <el-dialog
    v-model="visible"
    :title="`评分历史详情 - ${detailData.asset_ip || ''} @ ${
      detailData.calculated_at || detailData.score_time || ''
    }`"
    width="1200px"
    destroy-on-close
    @close="handleClose"
  >
    <div v-loading="loading" class="detail-content">
      <!-- 基础信息 -->
      <el-card class="detail-section-card">
        <template #header>
          <span class="section-title">基础信息</span>
        </template>
        <el-descriptions :column="4" border>
          <el-descriptions-item label="资产IP">
            <span class="monospace-text">{{ detailData.asset_ip || "-" }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="总分">
            <span :class="getScoreClass(detailData.total_score)">
              {{ detailData.total_score || "-" }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="风险等级">
            <div class="flex items-center">
              <span
                :class="`risk-indicator ${getRiskClass(detailData.risk_level)}`"
              ></span>
              <span>{{ getRiskText(detailData.risk_level) || "-" }}</span>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="评分时间">
            {{ detailData.calculated_at || detailData.score_time || "-" }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 变更信息 -->
      <el-card class="detail-section-card">
        <template #header>
          <span class="section-title">变更信息</span>
        </template>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="变更类型">
            {{ detailData.change_type || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="变更原因">
            {{ detailData.change_reason || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="分数变化">
            <span
              :style="{
                color:
                  (detailData.score_change || 0) >= 0 ? '#52c41a' : '#f5222d',
              }"
            >
              {{ (detailData.score_change || 0) >= 0 ? "+" : ""
              }}{{ detailData.score_change || 0 }} ({{
                detailData.old_score || 0
              }}
              → {{ detailData.total_score || 0 }})
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="风险变化">
            {{ detailData.risk_change || "-" }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 维度变更详情 -->
      <el-card class="detail-section-card">
        <template #header>
          <span class="section-title">维度变更详情</span>
        </template>
        <DynamicTable
          :columns="dimensionColumns"
          :data="detailData.dimension_changes || []"
        />
      </el-card>

      <!-- 完整评分数据 -->
      <el-card class="detail-section-card">
        <template #header>
          <span class="section-title">完整评分数据（JSON）</span>
        </template>
        <pre class="json-pre">{{
          JSON.stringify(detailData.full_data || {}, null, 2)
        }}</pre>
      </el-card>
    </div>

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button type="default" @click="handleViewCurrent"
        >查看当前评分</el-button
      >
      <el-button type="primary" @click="handleExportJson">导出JSON</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch, h } from "vue";
import { ElMessage } from "element-plus";
import { DynamicTable } from "@/components/DynamicTable";
import type { TableColumn } from "@/components/DynamicTable/types";
import { getHistoryDetail, getAssetScoreDetail } from "../../../servers";

// 定义属性和事件
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  detailId: {
    type: [String, Number],
    default: "",
  },
});

const emit = defineEmits(["close", "update:modelValue"]);

// 响应式数据
const visible = ref(props.modelValue);
const loading = ref(false);
const detailData = ref<any>({});

// 维度变更表格列配置
const dimensionColumns = ref<TableColumn[]>([
  {
    label: "维度名称",
    prop: "dimension_name",
    show: true,
  },
  {
    label: "旧扣分",
    prop: "old_deduction",
    align: "right",
    show: true,
    render: (row) => {
      return h("span", (row.old_deduction || 0).toFixed(2));
    },
  },
  {
    label: "新扣分",
    prop: "new_deduction",
    align: "right",
    show: true,
    render: (row) => {
      return h("span", (row.new_deduction || 0).toFixed(2));
    },
  },
  {
    label: "变化",
    prop: "change",
    align: "right",
    show: true,
    render: (row) => {
      const change = row.change || 0;
      const color = change > 0 ? "#f5222d" : change < 0 ? "#52c41a" : "#666";
      const icon = change > 0 ? "↑" : change < 0 ? "↓" : "—";
      return h("span", { style: { color, fontWeight: "bold" } }, [
        change > 0 ? "+" : "",
        change.toFixed(1),
        " ",
        icon,
      ]);
    },
  },
]);

// 监听显示状态变化
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
    if (val && props.detailId) {
      fetchDetailData(props.detailId);
  }
  },
  { immediate: true }
);

// 监听详情ID变化
watch(
  () => props.detailId,
  (id) => {
    if (id && visible.value) {
      fetchDetailData(id);
    }
  }
);

// 获取详情数据
const fetchDetailData = async (id: string | number) => {
  if (!id) return;

  loading.value = true;
  try {
    const { data } = await getHistoryDetail({ history_id: Number(id) });
    // 映射接口返回的数据到组件需要的格式
    detailData.value = {
      id: data.id,
      asset_ip: data.asset_ip,
      department: data.department,
      total_score: data.total_score,
      risk_level: data.risk_level,
      risk_level_desc: data.risk_level_desc,
      calculated_at: data.calculated_at,
      score_time: data.calculated_at, // 兼容旧字段名
      template_id: data.template_id,
      template_code: data.template_code,
      template_name: data.template_name,
      // 变更信息
      change_type:
        data.change_info?.change_type_desc || data.change_info?.change_type,
      change_reason: data.change_info?.change_reason,
      score_change: data.change_info?.score_change,
      old_score: data.change_info?.prev_score,
      risk_change: data.change_info?.risk_level_changed
        ? `${data.change_info.prev_risk_level} → ${data.risk_level}`
        : "无变化",
      // 维度变更
      dimension_changes: data.dimension_changes
        ? Object.keys(data.dimension_changes).map((key) => {
            const dim = data.dimension_changes[key];
            return {
              dimension_name: key,
              old_deduction: dim.old_deduction,
              new_deduction: dim.new_deduction,
              change: dim.change,
              reason: dim.reason,
            };
          })
        : [],
      // 完整数据
      full_data: data.full_snapshot || data,
    };
  } catch (error) {
    console.error("获取详情数据失败:", error);
    ElMessage.error("获取详情数据失败");
  } finally {
    loading.value = false;
  }
};

// 辅助函数 - 风险等级样式和文本
const getRiskClass = (level) => {
  const classMap = {
    low: "bg-success",
    medium: "bg-warning",
    high: "bg-orange-500",
    critical: "bg-danger",
  };
  return classMap[level] || "bg-gray-400";
};

const getRiskText = (level) => {
  const textMap = {
    low: "低风险",
    medium: "中等风险",
    high: "高风险",
    critical: "严重风险",
  };
  return textMap[level] || level;
};

// 辅助函数 - 分数样式
const getScoreClass = (score) => {
  if (!score) return "";
  if (score >= 80) return "text-success font-medium";
  if (score >= 60) return "text-warning font-medium";
  return "text-danger font-medium";
};

// 事件处理 - 关闭对话框
const handleClose = () => {
  emit("update:modelValue", false);
  emit("close");
};

// 事件处理 - 查看当前评分
const handleViewCurrent = async () => {
  if (!detailData.value.asset_ip) {
    ElMessage.warning("资产IP不能为空");
    return;
  }

  try {
    loading.value = true;
    const { data } = await getAssetScoreDetail({
      asset_ip: detailData.value.asset_ip,
      include_raw_data: true,
    });

    if (data) {
      // 将当前评分数据映射到详情格式
      detailData.value = {
        id: data.id || detailData.value.id,
        asset_ip: data.asset_ip,
        department: data.department,
        total_score: data.total_score,
        risk_level: data.risk_level,
        risk_level_desc: data.risk_level_desc,
        calculated_at: data.calculated_at,
        score_time: data.calculated_at,
        template_id: data.template_id,
        template_code: data.template_code,
        template_name: data.template_name,
        // 当前评分没有变更信息，标记为当前评分
        change_type: "当前评分",
        change_reason: "当前最新评分",
        score_change: null,
        old_score: null,
        risk_change: "当前评分",
        // 维度数据（如果有）
        dimension_changes: data.dimension_scores
          ? Object.keys(data.dimension_scores).map((key) => {
              const dim = data.dimension_scores[key];
              return {
                dimension_name: key,
                old_deduction: null,
                new_deduction: dim.deduction || 0,
                change: null,
                reason: "当前评分",
              };
            })
          : [],
        // 完整数据
        full_data: data,
      };

      ElMessage.success("已切换到当前评分详情");
    } else {
      ElMessage.error("获取当前评分失败");
    }
  } catch (error) {
    console.error("获取当前评分失败:", error);
    ElMessage.error("获取当前评分失败");
  } finally {
    loading.value = false;
  }
};

// 事件处理 - 导出JSON
const handleExportJson = () => {
  ElMessage.info("正在导出JSON数据...");
  // 导出JSON的逻辑
};
</script>

<style scoped lang="scss">
.detail-content {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.detail-section-card {
  margin-bottom: 16px;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.section-title {
  font-weight: 500;
  color: #1d2129;
}

.json-pre {
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 13px;
  overflow-x: auto;
  max-height: 200px;
}

.risk-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  display: inline-block;
  margin-right: 4px;
}

.monospace-text {
  font-family: monospace;
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 13px;
}
</style>
